﻿<template>
  <div class="star-bg"></div>
  <!-- 返回按鈕 -->
  
  <div class="badge-detail-container">
    <!-- 铭牌基本信息 -->
    <div v-if="badgeDetail" class="badge-info-card">
      <div class="badge-info-title">铭牌信息</div>
      <div class="badge-info-content">
        <div class="info-row"><span class="info-label">铭牌ID：</span>{{ badgeDetail.id }}</div>
        <div class="info-row"><span class="info-label">分区编码：</span>{{ getBadgeNameByAssociation(badgeDetail.association) }} Lv{{ badgeDetail.level }}</div>
        <div class="info-row"><span class="info-label">等级：</span>{{ badgeDetail.level }}</div>
        <div class="info-row"><span class="info-label">创建时间：</span>{{ formatDate(badgeDetail.createdAt) }}</div>
        <div class="info-row"><span class="info-label">评价：</span>{{ badgeDetail.evaluation || '暂无评价' }}</div>
      </div>
    </div>

    <!-- 贡献者列表 -->
    <div class="contributors-section" v-if="badgeDetail && badgeDetail.contributors">
      <div class="section-title">贡献者列表</div>
      <div class="contributors-table">
        <div class="contributors-header">
          <div>用户ID</div>
          <div>角色</div>
          <div>贡献比例</div>
          <div>状态</div>
        </div>
        <div v-for="c in badgeDetail.contributors" :key="c.uid" class="contributors-row">
          <div>{{ c.uid }}</div>
          <div>{{ c.role || '-' }}</div>
          <div>
            <div class="battery-bar">
              <div class="battery-bar-inner" :style="{width: c.percentage + '%', background: getBatteryColor(c.percentage)}"></div>
            </div>
            <span>{{ c.percentage }}%</span>
          </div>
          <div>{{ getStatusText(c.status) }}</div>
        </div>
      </div>
    </div>

    <!-- 统计信息 -->
    <div v-if="stats" class="stats-section">
      <div class="stats-card">
        <div class="stat-item">
          <div class="stat-value">{{ stats.badgeCount }}</div>
          <div class="stat-label">铭牌总数</div>
        </div>
        <div class="stat-item">
          <div class="stat-value">{{ stats.maxLevel }}</div>
          <div class="stat-label">最高等级</div>
        </div>
        <div class="stat-item">
          <div class="stat-value">{{ stats.avgLevel.toFixed(1) }}</div>
          <div class="stat-label">平均等级</div>
        </div>
      </div>
    </div>

    <!-- 词云展示 -->
    <section v-if="wordcloudData" class="wordcloud-section">
      <div class="section-title">词云</div>
      <qiun-data-charts
        type="wordCloud"
        :opts="wordCloudOpts"
        :chartData="wordCloudChartData"
        canvasId="wordcloud"
        style="width: 100%; height: 320px;"
      />
    </section>

    <!-- 相关任务列表 -->
    <div class="tasks-section">
      <div class="section-title">相关任务</div>
      
      <!-- 筛选器 - 手机端优化 -->
      <div class="tasks-filter">
        <div class="filter-row">
          <input v-model="filterForm.keyword" placeholder="关键词" class="input" />
          <!-- #ifdef H5 -->
          <select v-model="filterForm.status" class="input">
            <option value="">全部状态</option>
            <option value="1">未完成</option>
            <option value="2">进行中</option>
            <option value="3">已完成</option>
          </select>
          <!-- #endif -->
          <!-- #ifdef MP-WEIXIN -->
          <picker :range="statusOptions" :value="statusIndex" @change="onStatusPickerChange" class="input">
            <view class="uni-input">{{ statusOptions[statusIndex] }}</view>
          </picker>
          <!-- #endif -->
        </div>
        <div class="filter-row">
          <input v-model.number="filterForm.minReward" type="number" placeholder="最小奖励" class="input" />
          <input v-model.number="filterForm.maxReward" type="number" placeholder="最大奖励" class="input" />
        </div>
        <div class="filter-buttons">
          <button class="apex-btn" @click="handleFilter">筛选</button>
          <button class="apex-btn ghost" @click="resetFilter">重置</button>
        </div>
      </div>
      
      <!-- 任务列表 - 手机端卡片布局 -->
      <div class="tasks-list">
        <div v-for="task in tasksList" :key="task.taskId" class="task-card">
          <!-- 任务标题 -->
          <div class="task-title">{{ parseTaskData(task).title }}</div>
          
          <!-- 任务基本信息 -->
          <div class="task-info">
            <div class="info-item">
              <span class="info-label">奖励：</span>
              <span class="info-value reward">¥{{ parseTaskData(task).reward }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">发布时间：</span>
              <span class="info-value">{{ formatDate(parseTaskData(task).publishTime) }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">状态：</span>
              <span class="info-value status" :class="getTaskStatusClass(parseTaskData(task).status)">
                {{ getTaskStatusText(parseTaskData(task).status) }}
              </span>
            </div>
          </div>
          
          <!-- 铭牌信息 -->
          <div class="badges-section">
            <div class="badges-title">相关铭牌：</div>
            <div class="badges-list">
              <div v-for="badge in parseTaskData(task).badges" :key="badge.id" class="badge-item">
                <div class="badge-content">
                  <span class="badge-tag">
                    {{ getBadgeNameByAssociation(badge.association) }} Lv{{ badge.level }}
                    <span class="badge-percent">{{ getCurrentUserContribution(badge) }}%</span>
                  </span>
                  <div v-if="isCurrentUser" class="status-container">
                    <button 
                      class="status-btn" 
                      :class="getStatusClass(getCurrentUserStatus(badge))"
                      @click="toggleStatusMenu($event, badge.id)"
                    >
                      {{ getStatusText(getCurrentUserStatus(badge)) }}
                    </button>
                    <div class="status-menu" :id="`menu-${badge.id}`">
                      <div class="status-option" @click="handleBadgeCommand(badge.id, 0)">默认</div>
                      <div class="status-option" @click="handleBadgeCommand(badge.id, 1)">悬挂</div>
                      <div class="status-option" @click="handleBadgeCommand(badge.id, 2)">不公开</div>
                    </div>
                  </div>
                  <div v-else class="badge-status">
                    {{ getStatusText(getCurrentUserStatus(badge)) }}
                  </div>
                </div>
              </div>
            </div>
          </div>
          
          <!-- 操作按钮 -->
          <div class="task-actions">
            <button class="apex-btn primary" @click="viewTaskDetail(parseTaskData(task).taskId)">查看详情</button>
          </div>
        </div>
      </div>
      
      <!-- 分页 -->
      <div class="apex-pagination">
        <button class="apex-btn" :disabled="currentPage<=1" @click="handleCurrentChange(currentPage-1)">上一页</button>
        <span class="apex-page-info">第 {{ currentPage }} 页 / 共 {{ Math.ceil(totalElements/pageSize) }} 页</span>
        <button class="apex-btn" :disabled="currentPage>=Math.ceil(totalElements/pageSize)" @click="handleCurrentChange(currentPage+1)">下一页</button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, onBeforeUnmount, nextTick, watch } from 'vue'

import { getBadgeNameByAssociation } from '@/utils/skillUtils'
import { useUserStore } from '@/store/user'
import QiunDataCharts from '@/components/qiun-data-charts/qiun-data-charts.vue'
import BackButton from '@/components/BackButton.vue'

// 获取页面参数
const getPageParams = () => {
  const pages = getCurrentPages()
  const currentPage = pages[pages.length - 1]
  return currentPage?.options || {}
}

const routeParams = ref({})
const userStore = useUserStore()

// 数据状态
const badgeDetail = ref(null)
const stats = ref(null)
const tasksList = ref([])
const totalElements = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)
const wordcloudData = ref(null)

// 筛选表单
const filterForm = ref({
  keyword: '',
  status: null,
  minReward: null,
  maxReward: null,
  minLevel: null,
  maxLevel: null,
  startPublishTime: null,
  endPublishTime: null,
  startDeadline: null,
  endDeadline: null,
  priority1: null,
  direction1: null,
  priority2: null,
  direction2: null,
  priority3: null,
  direction3: null,
  priority4: null,
  direction4: null
})

const statusOptions = ['全部状态', '未完成', '进行中', '已完成'];
const statusIndex = ref(0);
function onStatusPickerChange(e) {
  statusIndex.value = e.detail.value;
  if (statusIndex.value == 0) filterForm.value.status = '';
  else if (statusIndex.value == 1) filterForm.value.status = '1';
  else if (statusIndex.value == 2) filterForm.value.status = '2';
  else if (statusIndex.value == 3) filterForm.value.status = '3';
}
watch(() => filterForm.value.status, (val) => {
  if (val === '') statusIndex.value = 0;
  else if (val === '1') statusIndex.value = 1;
  else if (val === '2') statusIndex.value = 2;
  else if (val === '3') statusIndex.value = 3;
});

// 计算属性：判断是否是当前用户
const isCurrentUser = computed(() => {
  return userStore.uid === routeParams.value.uid
})

// 获取铭牌详情
const fetchBadgeDetail = async () => {
  try {
    const contributorId = routeParams.value.uid
    const badges = routeParams.value.code
    if (!contributorId || !badges) {
      handleError('参数不完整')
      return
    }
    const token = uni.getStorageSync('accessToken')
    
    const [err, res] = await uni.request({
      url: '${NETWORK_CONFIG.API_BASE_URL}/badge/association',
      method: 'PATCH',
      data: null,
      header: {
        'Access-Token': `Bearer ${token}`,
        'Content-Type': 'application/json'
      },
      dataType: 'json',
      data: {
        contributorId,
        badges,
        page: currentPage.value - 1,
        size: pageSize.value,
        ...filterForm.value
      }
    })
    if (err) throw err;
    const { badge, stats: statsData, tasks, wordcloud } = res.data
    badgeDetail.value = badge
    stats.value = statsData
    tasksList.value = tasks.tasks
    totalElements.value = tasks.totalElements
    wordcloudData.value = wordcloud
    
    // 确保所有菜单都是关闭的
    setTimeout(() => {
      document.querySelectorAll('.status-menu').forEach(menu => {
        menu.classList.remove('show')
      })
    }, 100)

  } catch (error) {
    console.error('获取铭牌详情失败:', error)
    handleError('获取铭牌详情失败')
  }
}

// 工具函数
const formatDate = (dateString) => {
  if (!dateString) return '暂无'
  return new Date(dateString).toLocaleString()
}

const getStatusText = (status) => {
  const statusMap = {
    0: '默认',
    1: '悬挂',
    2: '不公开'
  }
  return statusMap[status] || '未知状态'
}

// 获取铭牌状态对应的类型
const getBadgeStatusType = (badge) => {
  const currentUid = routeParams.value.uid
  const contributor = badge.contributors.find(c => c.uid === Number(currentUid))
  const status = contributor ? contributor.status : 0

  const statusMap = {
    0: 'warning',  // 默认 - 黄色
    1: 'success',  // 悬挂 - 绿色
    2: 'danger'    // 不公开 - 红色
  }
  return statusMap[status] || 'warning'
}

// 处理铭牌下拉命令
const handleBadgeCommand = async (badgeId, command) => {
  try {
    // 先关闭菜单
    document.querySelectorAll('.status-menu').forEach(menu => {
      menu.classList.remove('show')
    })
    
    const token = uni.getStorageSync('accessToken')
    
    if (!token) {
      handleError('请先登录')
      return
    }

    const [err, res] = await uni.request({
      url: '${NETWORK_CONFIG.API_BASE_URL}/badge/changestatus',
      method: 'PATCH',
      data: null,
      header: {
        'Access-Token': `Bearer ${token}`
      },
      dataType: 'json',
      data: {
        badgeId: String(badgeId),
        status: Number(command)  // 确保status是数字类型
      }
    })
    if (err) throw err;

    if (res.data) {
      handleSuccess('状态更新成功')
      // 重新获取数据
      await fetchBadgeDetail()
    }
  } catch (error) {
    console.error('更新状态失败:', error)
    handleError(error.response?.data || '更新状态失败')
    // 重新获取数据以恢复状态
    await fetchBadgeDetail()
  }
}

const getTaskStatusText = (status) => {
  const statusMap = {
    1: '未完成',
    2: '进行中',
    3: '已完成'
  }
  return statusMap[status] || '未知状态'
}

const parseTaskData = (taskString) => {
  try {
    const data = typeof taskString === 'string' ? JSON.parse(taskString) : taskString
    // 确保badges数组中的每个badge对象都有正确的status属性
    if (data.badges) {
      data.badges = data.badges.map(badge => ({
        ...badge,
        status: Number(badge.status) // 确保status是数字类型
      }))
    }
    return data
  } catch (error) {
    console.error('解析任务数据失败:', error)
    return {}
  }
}

// 事件处理
const handleFilter = () => {
  currentPage.value = 1
  fetchBadgeDetail()
}

const resetFilter = () => {
  filterForm.value = {
    keyword: '',
    status: null,
    minReward: null,
    maxReward: null,
    minLevel: null,
    maxLevel: null,
    startPublishTime: null,
    endPublishTime: null,
    startDeadline: null,
    endDeadline: null,
    priority1: null,
    direction1: null,
    priority2: null,
    direction2: null,
    priority3: null,
    direction3: null,
    priority4: null,
    direction4: null
  }
  handleFilter()
}

const handleSizeChange = (val) => {
  pageSize.value = val
  fetchBadgeDetail()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchBadgeDetail()
}

const viewTaskDetail = (taskId) => {
  router.push(`/task?id=${taskId}`)
}

// 在 script setup 部分添加新的方法
const getCurrentUserContribution = (badge) => {
  const currentUid = routeParams.value.uid
  const contributor = badge.contributors.find(c => c.uid === Number(currentUid))
  return contributor ? contributor.percentage : 0
}

// 添加获取当前用户状态的方法
const getCurrentUserStatus = (badge) => {
  const currentUid = routeParams.value.uid
  const contributor = badge.contributors.find(c => c.uid === Number(currentUid))
  return contributor ? contributor.status : 0
}

function getBatteryColor(percentage) {
  if (percentage < 10) {
    return 'linear-gradient(90deg, #f44336, #ff9800)'; // 红橙
  } else if (percentage < 30) {
    return 'linear-gradient(90deg, #ff9800, #ffeb3b)'; // 橙黄
  } else {
    return 'linear-gradient(90deg, #4caf50, #8bc34a)'; // 绿色
  }
}

// 获取状态对应的样式类
const getStatusClass = (status) => {
  const statusMap = {
    0: 'status-default',
    1: 'status-hanging',
    2: 'status-private'
  }
  return statusMap[status] || 'status-default'
}

// 获取任务状态对应的样式类
const getTaskStatusClass = (status) => {
  const statusMap = {
    1: 'status-unfinished',
    2: 'status-ongoing',
    3: 'status-completed'
  }
  return statusMap[status] || 'status-unknown'
}

// 切换状态选择菜单
const toggleStatusMenu = (event, badgeId) => {
  event.stopPropagation() // 阻止事件冒泡
  
  // 关闭所有其他菜单
  document.querySelectorAll('.status-menu').forEach(menu => {
    if (menu.id !== `menu-${badgeId}`) {
      menu.classList.remove('show')
    }
  })
  
  const menu = document.getElementById(`menu-${badgeId}`)
  if (menu) {
    menu.classList.toggle('show')
  }
}

// 点击页面其他位置关闭菜单
const closeMenus = (event) => {
  if (!event.target.closest('.status-container')) {
    document.querySelectorAll('.status-menu').forEach(menu => {
      menu.classList.remove('show')
    })
  }
}

// 添加和移除全局点击事件
onMounted(() => {
  // 初始化路由参数
  routeParams.value = getPageParams()
  fetchBadgeDetail()
  document.addEventListener('click', closeMenus)
})

onBeforeUnmount(() => {
  document.removeEventListener('click', closeMenus)
})

const handleError = (message) => {
  uni.showToast({
    title: message,
    icon: 'none',
    duration: 2000
  })
}

const handleSuccess = (message) => {
  uni.showToast({
    title: message,
    icon: 'success',
    duration: 2000
  })
}

// 计算属性处理词云数据
const wordCloudChartData = computed(() => {
  if (!wordcloudData.value) return { series: [] }
  return {
    series: Object.entries(wordcloudData.value).map(([name, value]) => ({
      name,
      textSize: 16 + Math.random() * 24,
      color: `rgb(${Math.round(Math.random()*160)},${Math.round(Math.random()*160)},${Math.round(Math.random()*160)})`,
      value
    }))
  }
})
const wordCloudOpts = {}
</script>

<style scoped>
.star-bg {
  position: fixed;
  z-index: 0;
  left: 0; top: 0; width: 100vw; height: 100vh;
  background: #3a1c71;
  overflow: hidden;
}
.badge-detail-container {
  position: relative;
  z-index: 1;
  padding: 32px 0;
  max-width: 1200px;
  margin: 0 auto;
}
.badge-info-card, .stats-card, .tasks-section {
  background: #fff3;
  border-radius: 24px;
  margin-bottom: 32px;
  padding: 32px 40px;
  border: 2px solid #fff2;
}
.badge-info-title, .section-title {
  color: #a259ff;
  font-size: 1.7rem;
  font-weight: bold;
  margin-bottom: 22px;
  letter-spacing: 2px;
}
.info-row, .contributors-row, .tasks-row {
  display: flex;
  align-items: center;
  gap: 32px;
  padding: 12px 0;
  border-bottom: 1px solid #e0c3fc;
  font-size: 1.1rem;
}
.info-label {
  color: #a259ff;
  font-weight: bold;
  margin-right: 10px;
}
.contributors-header, .tasks-header {
  display: flex;
  gap: 32px;
  font-weight: bold;
  color: #a259ff;
  border-bottom: 2px solid #e0c3fc;
  padding-bottom: 10px;
  margin-bottom: 10px;
  font-size: 1.1rem;
}
.battery-bar {
  width: 60px;
  height: 14px;
  background: #f3e9ff;
  border-radius: 7px;
  overflow: hidden;
  display: inline-block;
  margin-right: 8px;
  border: 1.5px solid #a259ff;
}
.battery-bar-inner {
  height: 100%;
  border-radius: 6px 0 0 6px;
}
.stats-card {
  display: flex;
  justify-content: space-around;
  align-items: center;
}
.stat-item {
  text-align: center;
}
.stat-value {
  color: #a259ff;
  font-size: 2rem;
  font-weight: bold;
}
.stat-label {
  color: #fff;
  font-size: 1rem;
  margin-top: 6px;
}
.tasks-filter {
  display: flex;
  flex-direction: column;
  gap: 12px;
  margin-bottom: 20px;
}
.filter-row {
  display: flex;
  gap: 12px;
  flex-wrap: wrap;
}
.filter-buttons {
  display: flex;
  gap: 12px;
  justify-content: center;
}
.input {
  color: #00eaff;
  border: 1.5px solid #00eaff;
  border-radius: 8px;
  padding: 7px 18px;
  font-size: 1rem;
  font-weight: bold;
  outline: none;
  min-width: 110px;
}
.badge-tag {
  background: #fff3;
  color: #fff;
  border-radius: 8px;
  padding: 2px 10px;
  margin-right: 6px;
  font-weight: bold;
  font-size: 1rem;
  display: inline-block;
}
.badge-percent {
  color: #fff;
  margin-left: 4px;
  font-size: 0.95em;
}
.apex-btn {
  background: #00eaff;
  color: #fff;
  border: none;
  border-radius: 8px;
  padding: 6px 18px;
  font-size: 1rem;
  font-weight: bold;
}
.apex-btn.ghost {
  background: transparent;
  color: #00eaff;
  border: 1.5px solid #00eaff;
}
.apex-btn.primary {
  background: #a259ff;
  color: #fff;
  border: none;
  border-radius: 8px;
  padding: 8px 16px;
  font-size: 1rem;
  font-weight: bold;
}
.tasks-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}
.task-card {
  background: #fff2;
  border-radius: 16px;
  padding: 20px;
  border: 1px solid #fff2;
}
.task-title {
  font-size: 1.2rem;
  font-weight: bold;
  color: #fff;
  margin-bottom: 12px;
  line-height: 1.4;
}
.task-info {
  display: flex;
  flex-direction: column;
  gap: 8px;
  margin-bottom: 16px;
}
.info-item {
  display: flex;
  align-items: center;
  gap: 8px;
}
.info-label {
  color: #a259ff;
  font-weight: bold;
  font-size: 0.9rem;
  min-width: 80px;
}
.info-value {
  color: #fff;
  font-size: 0.9rem;
}
.info-value.reward {
  color: #ffd700;
  font-weight: bold;
  font-size: 1rem;
}
.info-value.status {
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 0.8rem;
  font-weight: bold;
}
.status-unfinished {
  background: #ffc10755;
  color: #ffc107;
  border: 1px solid #ffc10788;
}
.status-ongoing {
  background: #00c85355;
  color: #00c853;
  border: 1px solid #00c85388;
}
.status-completed {
  background: #2196f355;
  color: #2196f3;
  border: 1px solid #2196f388;
}
.status-unknown {
  background: #9e9e9e55;
  color: #9e9e9e;
  border: 1px solid #9e9e9e88;
}
.badges-section {
  margin-bottom: 16px;
}
.badges-title {
  color: #a259ff;
  font-weight: bold;
  font-size: 0.9rem;
  margin-bottom: 8px;
}
.badges-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
}
.badge-item {
  background: #fff1;
  border-radius: 8px;
  padding: 8px;
  border: 1px solid #fff1;
}
.badge-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 8px;
  flex-wrap: wrap;
}
.task-actions {
  display: flex;
  justify-content: center;
  margin-top: 12px;
}
.apex-pagination {
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 32px 0 0 0;
  gap: 18px;
}
.apex-page-info {
  color: #00eaff;
  font-size: 1.1rem;
  font-weight: bold;
  letter-spacing: 1px;
}
.wordcloud-section {
  background: #fff3;
  border-radius: 24px;
  margin-bottom: 32px;
  padding: 32px 40px;
  border: 2px solid #fff2;
}
</style>
